package com.mall.order.services;

import com.mall.commons.tool.exception.BizException;
import com.mall.order.OrderCoreService;
import com.mall.order.biz.TransOutboundInvoker;
import com.mall.order.biz.context.AbsTransHandlerContext;
import com.mall.order.biz.factory.OrderProcessPipelineFactory;
import com.mall.order.constant.OrderRetCode;
import com.mall.order.constants.OrderConstants;
import com.mall.order.dal.entitys.Order;
import com.mall.order.dal.persistence.OrderItemMapper;
import com.mall.order.dal.persistence.OrderMapper;
import com.mall.order.dal.persistence.OrderShippingMapper;
import com.mall.order.dto.*;
import com.mall.order.utils.ExceptionProcessorUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;

/**
 * 订单核心相关业务
 * @author Javid Xi
 * @version 1.0
 * @since 2021/7/20
 */
@Slf4j
@Component
@Service(cluster = "failfast")
public class OrderCoreServiceImpl implements OrderCoreService {

	@Autowired
	OrderMapper orderMapper;
	@Autowired
	OrderItemMapper orderItemMapper;
	@Autowired
	OrderShippingMapper orderShippingMapper;
	@Autowired
	OrderProcessPipelineFactory orderProcessPipelineFactory;


	/**
	 * 创建订单
	 * @param request 请求参数
	 * @return CreateOrderResponse
	 */
	@Override
	public CreateOrderResponse createOrder(CreateOrderRequest request) {
		CreateOrderResponse response = new CreateOrderResponse();
		try {
			//创建pipeline对象
			TransOutboundInvoker invoker = orderProcessPipelineFactory.build(request);
			//启动pipeline
			invoker.start(); //启动流程（pipeline来处理）
			//获取处理结果
			AbsTransHandlerContext context = invoker.getContext();
			//把处理结果转换为response
			response = (CreateOrderResponse) context.getConvert().convertCtx2Respond(context);
		} catch (Exception e) {
			log.error("OrderCoreServiceImpl.createOrder Occur Exception :" + e);
			ExceptionProcessorUtils.wrapperHandlerException(response, e);
		}
		return response;
	}

	/**
	 * 取消订单
	 * @param request 请求参数
	 * @return CancelOrderResponse
	 */
	@Override
	public CancelOrderResponse cancelOrder(CancelOrderRequest request) {
		// 响应封装类
		CancelOrderResponse response = new CancelOrderResponse();

		try {
			Order order = new Order();
			order.setCloseTime(new Date());
			order.setOrderId(request.getOrderId());
			order.setStatus(OrderConstants.ORDER_STATUS_TRANSACTION_CANCEL);
			request.requestCheck();
			// 更新订单状态
			int affectRows = orderMapper.updateByPrimaryKeySelective(order);
			if (affectRows != 1) {
				throw new BizException(OrderRetCode.DB_EXCEPTION.getCode(), OrderRetCode.DB_EXCEPTION.getMessage());
			}
			// 封装响应
			response.setCode(OrderRetCode.SUCCESS.getCode());
			response.setMsg(OrderRetCode.SUCCESS.getMessage());

		} catch (Exception e) {
			log.error("OrderCoreServiceImpl.cancelOrder Occur Exception :" + e);
			ExceptionProcessorUtils.wrapperHandlerException(response, e);
		}
		return response;

	}

	/**
	 * 删除订单
	 * @param request 请求参数
	 * @return DeleteOrderResponse
	 */
	@Override
	public DeleteOrderResponse deleteOrder(DeleteOrderRequest request) {
		// 响应封装类
		DeleteOrderResponse response = new DeleteOrderResponse();
		try {
			// 参数校验
			request.requestCheck();
			// 删除订单
			deleteOrderWithTransaction(request);
			// 封装响应
			response.setCode(OrderRetCode.SUCCESS.getCode());
			response.setMsg(OrderRetCode.SUCCESS.getMessage());
		} catch (Exception e) {
			log.error("OrderCoreServiceImpl.deleteOrder Occur Exception :" + e);
			ExceptionProcessorUtils.wrapperHandlerException(response, e);
		}
		return response;
	}

	/**
	 * 更新订单状态
	 * @param status 请求参数
	 * @param orderId 订单id
	 * @return UpdateOrderResponse
	 */
	@Override
	public UpdateOrderResponse updateOrder(Integer status, String orderId) {
		// 响应封装类
		UpdateOrderResponse response = new UpdateOrderResponse();

		try {
			Order order = new Order();
			order.setOrderId(orderId);
			order.setStatus(status);
			// 更新订单状态
			orderMapper.updateByPrimaryKeySelective(order);

			// 封装响应
			response.setCode(OrderRetCode.SUCCESS.getCode());
			response.setMsg(OrderRetCode.SUCCESS.getMessage());
		} catch (Exception e) {
			log.error("OrderCoreServiceImpl.updateOrder Occur Exception :" + e);
			ExceptionProcessorUtils.wrapperHandlerException(response, e);
		}
		return response;
	}

	/**
	 * 删除订单（事务）
	 * @param request 请求参数
	 */
	@Transactional(rollbackFor = Exception.class)
	@Override
	public void deleteOrderWithTransaction(DeleteOrderRequest request) {
		// 删除订单表
		orderMapper.deleteByPrimaryKey(request.getOrderId());
		// 删除订单商品表
		Example orderItemExample = new Example(Order.class);
		orderItemExample.createCriteria().andEqualTo("orderId",request.getOrderId());
		orderItemMapper.deleteByExample(orderItemExample);
		// 删除订单地址表
		orderShippingMapper.deleteByPrimaryKey(request.getOrderId());
	}
}
